/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.resource;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.cache.DataTypeCache;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.resource.AttributeService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.vo.Attribute;
import com.sinodata.bsm.common.vo.DataType;
import com.sinodata.bsm.common.vo.ResAttrVal;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author fanshengchao
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-7-7 上午10:04:11          fanshengchao        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class AttributeAction extends BaseAction<Attribute> {

    private Attribute entity;
    private Long id;

    @Autowired
    private DataTypeCache dataTypeCache;

    @Autowired
    private AttributeService attributeService;

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#delete()
     */
    @Override
    public String delete() throws Exception {

        //删除自定义属性时，判断是否有给自定义的属性添加值,有则删除自定义属性的值
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
        ResAttrVal attrVal = attributeService.getResAttrVal(resId, id);
        JSONObject object = new JSONObject();
        if (attrVal != null) {
            object.element("flag", "false");
            object.element("info", "属性已被引用,不能删除");
        } else {
            object.element("flag", "true");
            attributeService.deleteAttributeById(id);
        }
        Struts2Utils.renderJson(object);
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#input()
     */
    @Override
    public String input() throws Exception {
        List<DataType> dataTypes = dataTypeCache.getAll();
        Struts2Utils.setRequestAttribute("dataTypes", dataTypes);
        Struts2Utils.setRequestAttribute("resId", Struts2Utils.getParameter("resId"));
        return "input";
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#list()
     */
    @Override
    public String list() throws Exception {
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));

        List<Attribute> list = attributeService.findAttributeByResId(resId);
        JSONArray attributes = new JSONArray();
        JSONObject json = new JSONObject();

        for (int i = 0; list != null && i < list.size(); i++) {
            Attribute attribute = list.get(i);

            JSONObject entity = new JSONObject();
            entity.element("operate", "");
            entity.element("name", attribute.getName() == null ? "" : attribute.getName());
            entity.element("code", attribute.getCode() == null ? "" : attribute.getCode());
            DataType dataType = dataTypeCache.get(attribute.getDataTypeId());
            entity.element("dataTypeName", dataType.getName());
            entity.element("desc", attribute.getDesc() == null ? "" : attribute.getDesc());
            entity.element("id", attribute.getId());
            entity.element("dataTypeId", dataType.getId());
            attributes.add(entity);
        }

        json.element("aaData", attributes);
        json.element("iTotalRecords", 0);
        json.element("iTotalDisplayRecords", 0);

        Struts2Utils.renderText(json.toString());
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#prepareModel()
     */
    @Override
    protected void prepareModel() throws Exception {
        if (id == null) {
            entity = new Attribute();
        } else {
            entity = attributeService.getAttributeById(id);
        }
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#save()
     */
    @Override
    public String save() throws Exception {
        attributeService.saveOrUpdateAttribute(entity);
        return null;
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.ModelDriven#getModel()
     */
    //属性自定义页面
    public String common() {
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
        boolean hasPrivilege = UserFunctionValidate.resFunctionValidate(resId, FunctionConstants.EDIT_RES);
        Struts2Utils.setRequestAttribute("hasEditResPrivilege", hasPrivilege);
        Struts2Utils.setRequestAttribute("resId", resId);
        return "common";
    }

    public String initUpdate() {
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
        List<DataType> dataTypes = dataTypeCache.getAll();
        Attribute attribute = attributeService.getAttributeById(id);

        Struts2Utils.setRequestAttribute("attribute", attribute);
        Struts2Utils.setRequestAttribute("dataTypes", dataTypes);
        Struts2Utils.setRequestAttribute("resId", resId);
        return "update";
    }

    /**
     * 资源的自定义属性和默认属性  主要用于事件管理-资源查询 资源详细信息的查看
     * @return
     */
    public String attributes() {
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
        Long resTypeId = Long.parseLong(Struts2Utils.getParameter("resTypeId"));

        List<Attribute> showAttribute = new ArrayList<Attribute>();
        //默认属性
        ResTypeBean typeBean = ResTypeBean.get(resTypeId);
        List<Attribute> defaultAttribute = typeBean.attributes();
        if (defaultAttribute != null) {
            showAttribute.addAll(defaultAttribute);
        }

        //自定义属性
        List<Attribute> customAttribute = attributeService.findAttributeByResId(resId);
        if (customAttribute != null) {
            showAttribute.addAll(customAttribute);
        }

        JSONArray array = new JSONArray();
        for (Attribute attribute : showAttribute) {
            JSONObject object = new JSONObject();
            object.element("id", attribute.getId());
            object.element("name", attribute.getName().trim());

            ResAttrVal val = attributeService.getResAttrVal(resId, attribute.getId());
            object.element("attrValue", val == null ? "" : val.getAttrValue());
            array.add(object);
        }

        Struts2Utils.renderJson(array);
        return null;
    }

    /**
     * 属性是否删除
     * 
     * @return true:已删除 false:未删除
     */
    public String isDelete() {
        Struts2Utils.renderText(" " + (attributeService.getAttributeById(id) == null) + " ");
        return null;
    }

    /**
     * 属性名称重复验证
     * @return
     */
    public String repeatNameValidate() {
        try {
            String name = Struts2Utils.getParameter("name");
            boolean flag = false;
            Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
            List<Attribute> attributes = attributeService.findAttributeByResId(resId);
            Attribute entity = attributeService.getAttributeById(id);
            for (int i = 0; attributes != null && i < attributes.size(); i++) {
                Attribute attribute = attributes.get(i);
                if (attribute.getName().equals(name) && entity == null) {
                    flag = true;
                    break;
                }

                //修改时验证
                if (entity != null && attribute.getId().intValue() != entity.getId().intValue() && name.equals(attribute.getName())) {
                    flag = true;
                    break;
                }
            }
            Struts2Utils.renderText("" + flag + "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Attribute getModel() {
        // TODO Auto-generated method stub
        return entity;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
